﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace SharpSoft.Web
{
    public class PermissionRequirement : IAuthorizationRequirement
    {

    }
    public class PermissionAuthorizationHandler : AuthorizationHandler<PermissionRequirement>
    {
        public PermissionAuthorizationHandler()
        {

        }

        public override Task HandleAsync(AuthorizationHandlerContext context)
        {
            return base.HandleAsync(context);
        }
        protected async override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
        {
            if (context.User.HasClaim(c => c.Type == "isrootuser" && bool.Parse(c.Value)))
            {//根账号跳过权限检查
                context.Succeed(requirement);
            }
            var ac = context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext;


            //  

            if (ac != null)
            {
                string area = "";
                string controller = "";
                string action = "";
                string extFlag = "";
                var routeDic = ac.RouteData.Values;
                if (routeDic != null)
                {
                    if (routeDic.ContainsKey("area"))
                    {
                        area = $"{routeDic["area"]}";
                    }
                    if (routeDic.ContainsKey("controller"))
                    {
                        controller = $"{routeDic["controller"]}";
                    }
                    if (routeDic.ContainsKey("action"))
                    {
                        action = $"{routeDic["action"]}";
                    }
                }
                if (ac.ActionDescriptor is Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor cad)
                {
                    var atts = cad.MethodInfo.GetCustomAttributes(typeof(PermissionAuthorizeAttribute), true);
                    foreach (PermissionAuthorizeAttribute item in atts)
                    {
                        extFlag = item.ExtensionFlag;
                    }
                }
                var ad = ac.ActionDescriptor;

                var pername = AuthorizeProvider.CreatePermissionName(area, controller, action, extFlag);

                var u = context.User;
                var apppUser = HttpContextExtensions.GetAppUser(context.User);

                var enable = apppUser.GetPermissionEnabled(pername);
                if (!enable)
                {
                    context.Fail();
                    return;
                }
            }
            context.Succeed(requirement);
            await Task.Delay(1);
        }
    }
}
